import { LoginApi, RegisterApi } from "@/api";
import React, { useState } from "react";
import logo from "@/assets/images/logo.png";
import { Button, TextField } from "@mui/material";
import "./login.less";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { Dispatch } from "redux";
import { useToast, useToastSuccess } from "@/utils/toast";
export default function Login() {
  //用一个标记判断注册还是登录
  const [isLoginPage, setIsLoginPage] = useState(true);
  // 用户名和密码
  const [username, setUserName] = useState("17628326441");
  const [password, setPassword] = useState("wolfcode123");
  const toastsuccess = useToastSuccess();
  const navigate = useNavigate();
  const login = () => {
    LoginApi({
      password,
      username,
    }).then((res) => {
      if (res.errCode === 0) {
        localStorage.setItem("token", res.data);
        // alert("登录成功");
        toastsuccess("登录成功");
        navigate("/home");
      }
    });
  };

  const register = () => {
    //注册的逻辑
    RegisterApi({
      phone: username,
      password,
    }).then((res) => {
      if (res.errCode === 0) {
        toastsuccess("注册成功");
        // 去登录
        setIsLoginPage(true);
      }
    });
  };
  const btnClick = () => {
    //验证数据的完整
    //用户名。密码是否为空
    //手机号的格式是否正确
    isLoginPage ? login() : register();
  };
  return (
    <div className="login">
      <img src={logo} alt="" />
      <section className="form">
        <TextField
          variant="outlined"
          placeholder="请输入手机号"
          value={username}
          onChange={(e) => setUserName(e.target.value)}
        />
        <TextField
          variant="outlined"
          type="password"
          placeholder="请输入密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <Button onClick={btnClick} variant="contained">
          {isLoginPage ? "登录" : "注册"}
        </Button>
      </section>
      <div className="exchange">
        <span onClick={() => setIsLoginPage(!isLoginPage)}>
          去{isLoginPage ? "注册" : "登录"}
        </span>
      </div>
    </div>
  );
}
